package com.example.learn_spring_boot3.interecepror;

import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PerformanceInterceptor implements HandlerInterceptor {

    private static final ThreadLocal<Long> startTimeThreadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录请求开始时间
        startTimeThreadLocal.set(System.currentTimeMillis());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 计算接口执行时间
        long endTime = System.currentTimeMillis();
        long startTime = startTimeThreadLocal.get();
        long duration = endTime - startTime;
        System.out.println(request.getRequestURI() + " 执行时间: " + duration + "ms");
        // 清理ThreadLocal，防止内存泄漏
        startTimeThreadLocal.remove();
    }
}